//
//  DR_ImagePickerTool.swift
//  DocReaderRP
//
//  Created by  mac on 2025/11/14.
//

import UIKit
import Photos
import PhotosUI

class DR_ImagePickerTool: NSObject {
    
    static let shared = DR_ImagePickerTool()
    
    // 回调：选中图片后返回图片数组
    private var completion: (([UIImage]) -> Void)?
    private weak var presentingViewController: UIViewController?
    
    private override init() {
        super.init()
    }
    
    // MARK: - 公开方法：打开相册选择图片（多选）
    /// 打开相册选择图片，支持多选
    /// - Parameters:
    ///   - viewController: 用于展示相册选择器的 ViewController
    ///   - completion: 选择完成后的回调，返回选中的图片数组
    func presentPhotoPicker(from viewController: UIViewController, completion: @escaping ([UIImage]) -> Void) {
        self.presentingViewController = viewController
        self.completion = completion
        
        checkPhotoLibraryPermission()
    }
    
    // MARK: - 相册权限检查
    private func checkPhotoLibraryPermission() {
        guard let viewController = presentingViewController else { return }
        
        let status = PHPhotoLibrary.authorizationStatus(for: .readWrite)
        
        switch status {
        case .authorized, .limited:
            // 已授权，打开相册
            presentPhotoPicker()
            
        case .notDetermined:
            // 未请求过权限，请求权限
            PHPhotoLibrary.requestAuthorization(for: .readWrite) { [weak self] newStatus in
                DispatchQueue.main.async {
                    if newStatus == .authorized || newStatus == .limited {
                        self?.presentPhotoPicker()
                    } else {
                        // 用户拒绝授权
                        self?.showPermissionDeniedAlert()
                    }
                }
            }
            
        case .denied, .restricted:
            // 用户主动拒绝或受限制，显示提示
            showPermissionDeniedAlert()
            
        @unknown default:
            showPermissionDeniedAlert()
        }
    }
    
    // MARK: - 打开相册选择器（多选）
    private func presentPhotoPicker() {
        guard let viewController = presentingViewController else {
            print("⚠️ [DR_ImagePickerTool] 无法获取 ViewController")
            return
        }
        
        if #available(iOS 14.0, *) {
            var configuration = PHPickerConfiguration()
            configuration.selectionLimit = 0 // 0 表示无限制多选
            configuration.filter = .images // 只显示图片
            
            let picker = PHPickerViewController(configuration: configuration)
            picker.delegate = self
            viewController.present(picker, animated: true)
        } else {
            // iOS 13 及以下使用 UIImagePickerController（只能单选）
            let picker = UIImagePickerController()
            picker.sourceType = .photoLibrary
            picker.delegate = self
            viewController.present(picker, animated: true)
        }
    }
    
    // MARK: - 显示权限被拒绝的提示
    private func showPermissionDeniedAlert() {
        guard let viewController = presentingViewController else { return }
        
        let alert = UIAlertController(
            title: "需要相册权限",
            message: "请在设置中允许访问相册，以便选择图片转换为PDF",
            preferredStyle: .alert
        )
        
        alert.addAction(UIAlertAction(title: "取消", style: .cancel))
        alert.addAction(UIAlertAction(title: "去设置", style: .default) { [weak self] _ in
            self?.openSettings()
        })
        
        viewController.present(alert, animated: true)
    }
    
    // MARK: - 跳转到设置中心
    private func openSettings() {
        if let settingsURL = URL(string: UIApplication.openSettingsURLString) {
            UIApplication.shared.open(settingsURL)
        }
    }
    
    // MARK: - 处理选中的图片
    private func handleSelectedImages(_ images: [UIImage]) {
        guard !images.isEmpty else { return }
        completion?(images)
        // 清空回调，避免内存泄漏
        completion = nil
        presentingViewController = nil
    }
}

// MARK: - PHPickerViewControllerDelegate (iOS 14+)
@available(iOS 14.0, *)
extension DR_ImagePickerTool: PHPickerViewControllerDelegate {
    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
        picker.dismiss(animated: true)
        
        guard !results.isEmpty else {
            // 用户取消选择
            completion = nil
            presentingViewController = nil
            return
        }
        
        var selectedImages: [UIImage] = []
        let group = DispatchGroup()
        
        for result in results {
            group.enter()
            result.itemProvider.loadObject(ofClass: UIImage.self) { object, error in
                defer { group.leave() }
                if let image = object as? UIImage {
                    selectedImages.append(image)
                } else if let error = error {
                    print("⚠️ [DR_ImagePickerTool] 加载图片失败: \(error.localizedDescription)")
                }
            }
        }
        
        group.notify(queue: .main) { [weak self] in
            self?.handleSelectedImages(selectedImages)
        }
    }
}

// MARK: - UIImagePickerControllerDelegate (iOS 13 及以下)
extension DR_ImagePickerTool: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true)
        
        if let image = info[.originalImage] as? UIImage {
            handleSelectedImages([image])
        }
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true)
        // 用户取消选择
        completion = nil
        presentingViewController = nil
    }
}
